package com.bbcare.switchData.controller;

import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.bbcare.comm.*;
import com.bbcare.department.plat.service.impl.DepartmentBasicService;
import com.bbcare.followup.plat.entity.*;
import com.bbcare.followup.plat.service.*;
import com.bbcare.followup.plat.service.impl.FollowQueueService;
import com.bbcare.followup.plat.service.impl.PatientService;
import com.bbcare.followup.plat.store.ibatis.IFollowTaskDAO;
import com.bbcare.followup.plat.store.ibatis.IPatientDAO;
import com.bbcare.followup.plat.store.ibatis.IPatientQueueSchemeDAO;
import com.bbcare.followup.plat.store.ibatis.IPatientTaskContentDAO;
import com.bbcare.followup.plat.task.TaskComparatorDesc;
import com.bbcare.switchData.entity.model.FuInformruleDict;
import com.bbcare.switchData.entity.model.PtAccountInfo;
import com.bbcare.switchData.entity.model.PtDevelopstandardData;
import com.bbcare.switchData.entity.model.PtEvaluationGuide;
import com.bbcare.switchData.entity.model.*;
import com.bbcare.switchData.service.IWxApletService;
import com.bbcare.treat.plat.service.impl.PatientArchService;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import redis.clients.jedis.JedisPool;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;


@Controller
@RequestMapping(value = "/switchData/wxApletRecord")
public class WxApletController {
    private final Log log = LogFactory.getLog(WxApletController.class);

    @Resource(name = "jedisPool")
    private JedisPool jedisPool;
    @Autowired
    private IWxApletService wxApletService;

    @Autowired
    private IFollowEvaluationService followEvaluationService;

    @Autowired
    private IPatientService patientService;

    @Autowired
    private PatientArchService patientArchService;

    @Autowired
    private FollowQueueService followQueueSerivce;

    @Autowired
    private DepartmentBasicService departmentBasicService;

    @Autowired
    private IPatientDAO iPatientDAO;

    @Autowired
    private IPatientQueueSchemeDAO iPatientQueueSchemeDAO;

    @Autowired
    private PatientService patientSerivce;

    @Autowired
    private IPatientTaskContentDAO patientTaskContentDAO;

    @Autowired
    private IPatientPhoneService patientPhoneService;

    @Autowired
    private IFamilyReportService familyReportService;

    @Autowired
    private IFollowTaskDAO followTaskDAO;


    @Autowired
    private IPatientQueueSchemeDAO patientQueueSchemeDAO;

    @Autowired
    private IMessageNotifyRecordService messageNotifyRecordService;


    //1
    @ResponseBody
    @RequestMapping(value = "/selectByProperties1")
    public ResultModel selectByProperties1(@RequestBody String requestBody) {
        log.info("1-->" + requestBody);
        JSONObject jsonObject = JSON.parseObject(requestBody);
        jsonObject = jsonObject.getJSONObject("data");
        if (jsonObject.isEmpty()) {
            return new ResultModel<Object>("查询数据错误");
        }
        Map<String, Object> params = page(jsonObject);

        List<PtAccountInfo> list = wxApletService.selectByProperties1(params);
        return new ResultModel<Object>(list);
    }

    //2
    @ResponseBody
    @RequestMapping(value = "/selectByPropertiesWithDeptId2", produces = "application/json; charset=utf-8")
    public ResultModel selectByPropertiesWithDeptId2(@RequestBody String requestBody) {
        log.info("2-->" + requestBody);
        JSONObject jsonObject = JSON.parseObject(requestBody);
        jsonObject = jsonObject.getJSONObject("data");
        if (jsonObject.isEmpty()) {
            return new ResultModel<Object>("查询数据错误");
        }
        Map<String, Object> params = page(jsonObject);
        List<PtUserInfo> list = wxApletService.selectByPropertiesWithDeptId2(params);
        return new ResultModel<Object>(list);
    }

    //3
    @ResponseBody
    @RequestMapping(value = "/selectByUserIds3")
    public ResultModel selectByUserIds3(@RequestBody String requestBody) {
        log.info("3-->" + requestBody);
        JSONObject jsonObject = JSON.parseObject(requestBody);
        jsonObject = jsonObject.getJSONObject("data");
        if (jsonObject.isEmpty()) {
            return new ResultModel<Object>("查询数据错误");
        }
        List<String> userids = JSONObject.parseArray(jsonObject.getJSONObject("params").getString("userIds"), String.class);
        List<PtQueueschemeInfo> list = wxApletService.selectByUserIds3(userids);
        return new ResultModel<Object>(list);
    }

    //4
    @ResponseBody
    @RequestMapping(value = "/selectByProperties4")
    public ResultModel selectByProperties4(@RequestBody String requestBody) {
        log.info("4-->" + requestBody);
        JSONObject jsonObject = JSON.parseObject(requestBody);
        jsonObject = jsonObject.getJSONObject("data");
        if (jsonObject.isEmpty()) {
            return new ResultModel<Object>("查询数据错误");
        }
        Map<String, Object> params = page(jsonObject);
        List<FuQueueInfo> list = wxApletService.selectByProperties4(params);
        return new ResultModel<Object>(list);
    }

    //5
    @ResponseBody
    @RequestMapping(value = "/selectByTaskId5")
    public ResultModel selectByTaskId5(@RequestBody String requestBody) {
        log.info("5-->" + requestBody);
        JSONObject jsonObject = JSON.parseObject(requestBody);
        jsonObject = jsonObject.getJSONObject("data");
        if (jsonObject.isEmpty()) {
            return new ResultModel<Object>("查询数据错误");
        }
        Map<String, Object> params = page(jsonObject);
        List<PtTaskcontentInfo> list = wxApletService.selectByTaskId5(params);
        return new ResultModel<Object>(list);
    }

    //6
    @ResponseBody
    @RequestMapping(value = "/selectByTaskIds6")
    public ResultModel selectByTaskIds6(@RequestBody String requestBody) {
        log.info("6-->" + requestBody);
        JSONObject jsonObject = JSON.parseObject(requestBody);
        jsonObject = jsonObject.getJSONObject("data");
        if (jsonObject.isEmpty()) {
            return new ResultModel<Object>("查询数据错误");
        }
        List<String> taskIds = JSONObject.parseArray(jsonObject.getJSONObject("params").getString("taskIds"), String.class);
        List<PtTaskcontentInfo> list = wxApletService.selectByTaskIds6(taskIds);
        return new ResultModel<Object>(list);
    }

    //7
    @ResponseBody
    @RequestMapping(value = "/selectByTaskIds7")
    public ResultModel selectByTaskIds7(@RequestBody String requestBody) {
        log.info("7-->" + requestBody);
        JSONObject jsonObject = JSON.parseObject(requestBody);
        jsonObject = jsonObject.getJSONObject("data");
        if (jsonObject.isEmpty()) {
            return new ResultModel<Object>("查询数据错误");
        }
        List<String> taskIds = JSONObject.parseArray(jsonObject.getJSONObject("params").getString("taskIds"), String.class);
        List<PtContentdataInfo> list = wxApletService.selectByTaskIds7(taskIds);
        return new ResultModel<Object>(list);
    }

    //8
    @ResponseBody
    @RequestMapping(value = "/selectByTemplId8")
    public ResultModel selectByTemplId8(@RequestBody String requestBody) {
        log.info("8-->" + requestBody);
        JSONObject jsonObject = JSON.parseObject(requestBody);
        jsonObject = jsonObject.getJSONObject("data");
        if (jsonObject.isEmpty()) {
            return new ResultModel<Object>("查询数据错误");
        }
        Map<String, Object> params = page(jsonObject);
        List<FuContenttemplversionDict> list = wxApletService.selectByTemplId8(params);
        return new ResultModel<Object>(list);
    }

    //9
    @ResponseBody
    @RequestMapping(value = "/selectByEvaluationIds9")
    public ResultModel selectByEvaluationIds9(@RequestBody String requestBody) {
        log.info("9-->" + requestBody);
        JSONObject jsonObject = JSON.parseObject(requestBody);
        jsonObject = jsonObject.getJSONObject("data");
        if (jsonObject.isEmpty()) {
            return new ResultModel<Object>("查询数据错误");
        }
        List<String> evaluationIds = JSONObject.parseArray(jsonObject.getJSONObject("params").getString("evaluationIds"), String.class);
        List<PtEvaluationGuide> list = wxApletService.selectByEvaluationIds9(evaluationIds);
        return new ResultModel<Object>(list);
    }

    //10
    @ResponseBody
    @RequestMapping(value = "/selectByUserIds10")
    public ResultModel selectByUserIds10(@RequestBody String requestBody) {
        log.info("10-->" + requestBody);
        JSONObject jsonObject = JSON.parseObject(requestBody);
        jsonObject = jsonObject.getJSONObject("data");
        if (jsonObject.isEmpty()) {
            return new ResultModel<Object>("查询数据错误");
        }
        List<String> ptUserInfos = JSONObject.parseArray(jsonObject.getJSONObject("params").getString("ptUserInfos"), String.class);
        List<PtTaskInfo> list = wxApletService.selectByUserIds10(ptUserInfos);
        return new ResultModel<Object>(list);
    }

    //11
    @ResponseBody
    @RequestMapping(value = "/selectByPage11")
    public ResultModel selectByPage11(@RequestBody String requestBody) {
        log.info("11-->" + requestBody);
        JSONObject jsonObject = JSON.parseObject(requestBody);
        jsonObject = jsonObject.getJSONObject("data");
        if (jsonObject.isEmpty()) {
            return new ResultModel<Object>("查询数据错误");
        }
        Map<String, Object> params = page(jsonObject);
        List<DeptEducationContent> list = wxApletService.selectByPage11(params);
        return new ResultModel<Object>(list);
    }

    //12
    @ResponseBody
    @RequestMapping(value = "/selectByUserIds12")
    public ResultModel selectByUserIds12(@RequestBody String requestBody) {
        log.info("12-->" + requestBody);
        JSONObject jsonObject = JSON.parseObject(requestBody);
        jsonObject = jsonObject.getJSONObject("data");
        if (jsonObject.isEmpty()) {
            return new ResultModel<Object>("查询数据错误");
        }
        List<String> userIds = JSONObject.parseArray(jsonObject.getJSONObject("params").getString("userIds"), String.class);
        List<PtGrowthRecord> list = wxApletService.selectByUserIds12(userIds);
        return new ResultModel<Object>(list);
    }

    //13
    @ResponseBody
    @RequestMapping(value = "/selectByPrimaryKey13")
    public ResultModel selectByPrimaryKey13(@RequestBody String requestBody) {
        log.info("13-->" + requestBody);
        JSONObject jsonObject = JSON.parseObject(requestBody);
        jsonObject = jsonObject.getJSONObject("data");
        if (jsonObject.isEmpty()) {
            return new ResultModel<Object>("查询数据错误");
        }
        Map<String, Object> params = page(jsonObject);
        List<PtTaskInfo> list = wxApletService.selectByPrimaryKey13(params);
        if (list.size() > 0) {
            return new ResultModel<Object>(list.get(0));
        }
        return new ResultModel<Object>("{}");

    }

    //14
    @ResponseBody
    @RequestMapping(value = "/selectBySearchVo14")
    public ResultModel selectBySearchVo14(@RequestBody String requestBody) {
        log.info("14-->" + requestBody);
        JSONObject jsonObject = JSON.parseObject(requestBody);
        jsonObject = jsonObject.getJSONObject("data");
        if (jsonObject.isEmpty()) {
            return new ResultModel<Object>("查询数据错误");
        }
        PtTaskInfoSearchVo vo = JSONObject.parseObject(jsonObject.getJSONObject("params").getString("ptTaskInfoSearchVo"), PtTaskInfoSearchVo.class);
        List<PtTaskInfoSearchVo> list = wxApletService.selectBySearchVo14(vo);
        return new ResultModel<Object>(list);
    }

    //15
    @ResponseBody
    @RequestMapping(value = "/selectByProperties15")
    public ResultModel selectByProperties15(@RequestBody String requestBody) {
        log.info("15-->" + requestBody);
        JSONObject jsonObject = JSON.parseObject(requestBody);
        jsonObject = jsonObject.getJSONObject("data");
        if (jsonObject.isEmpty()) {
            return new ResultModel<Object>("查询数据错误");
        }
        Map<String, Object> params = page(jsonObject);
        List<FuInformruleDict> list = wxApletService.selectByProperties15(params);
        return new ResultModel<Object>(list);
    }

    //16
    @ResponseBody
    @RequestMapping(value = "/selectByPrimaryKey16")
    public ResultModel selectByPrimaryKey16(@RequestBody String requestBody) {
        log.info("16-->" + requestBody);
        JSONObject jsonObject = JSON.parseObject(requestBody);
        jsonObject = jsonObject.getJSONObject("data");
        if (jsonObject.isEmpty()) {
            return new ResultModel<Object>("查询数据错误");
        }
        Map<String, Object> params = page(jsonObject);
        List<PtGrowthRecord> list = wxApletService.selectByPrimaryKey16(params);
        if (list.size() > 0) {
            return new ResultModel<Object>(list.get(0));
        }
        return new ResultModel<Object>("{}");
    }

    //17
    @ResponseBody
    @RequestMapping(value = "/selectHealthGuideDetail17")
    public ResultModel selectHealthGuideDetail17(@RequestBody String requestBody) {
        log.info("17-->" + requestBody);
        JSONObject jsonObject = JSON.parseObject(requestBody);
        jsonObject = jsonObject.getJSONObject("data");
        if (jsonObject.isEmpty()) {
            return new ResultModel<Object>("查询数据错误");
        }
        Map<String, Object> params = page(jsonObject);
        //t_healthguidedetai
        List<Map<String, Object>> list = wxApletService.selectHealthGuideDetail17(params);

        return new ResultModel<Object>(list);
    }

    //18
    @ResponseBody
    @RequestMapping(value = "/selectByProperties18")
    public ResultModel selectByProperties18(@RequestBody String requestBody) {
        log.info("18-->" + requestBody);
        JSONObject jsonObject = JSON.parseObject(requestBody);
        jsonObject = jsonObject.getJSONObject("data");
        if (jsonObject.isEmpty()) {
            return new ResultModel<Object>("查询数据错误");
        }
        Map<String, Object> params = page(jsonObject);

        List<PtDevelopstandardData> list = wxApletService.selectByProperties18(params);

        return new ResultModel<Object>(list);
    }

    //19
    @ResponseBody
    @RequestMapping(value = "/selectStandardwfhList19")
    public ResultModel selectStandardwfhList19(@RequestBody String requestBody) {
        log.info("19-->" + requestBody);
        JSONObject jsonObject = JSON.parseObject(requestBody);
        jsonObject = jsonObject.getJSONObject("data");
        if (jsonObject.isEmpty()) {
            return new ResultModel<Object>("查询数据错误");
        }
        Map<String, Object> params = page(jsonObject);
        List<PtDevelopstandardData> list = wxApletService.selectStandardwfhList19(params);

        return new ResultModel<Object>(list);
    }

    //20
    @ResponseBody
    @RequestMapping(value = "/selectByPropertiesAndCorrectAge20")
    public ResultModel selectByPropertiesAndCorrectAge20(@RequestBody String requestBody) {
        log.info("20-->" + requestBody);
        JSONObject jsonObject = JSON.parseObject(requestBody);
        jsonObject = jsonObject.getJSONObject("data");
        if (jsonObject.isEmpty()) {
            return new ResultModel<Object>("查询数据错误");
        }
        Map<String, Object> params = page(jsonObject);
        List<PtDevelopstandardData> list = wxApletService.selectByPropertiesAndCorrectAge20(params);

        return new ResultModel<Object>(list);
    }

    //21
    @ResponseBody
    @RequestMapping(value = "/selectByPrimaryKey21")
    public ResultModel selectByPrimaryKey21(@RequestBody String requestBody) {
        log.info("21-->" + requestBody);
        JSONObject jsonObject = JSON.parseObject(requestBody);
        jsonObject = jsonObject.getJSONObject("data");
        if (jsonObject.isEmpty()) {
            return new ResultModel<Object>("查询数据错误");
        }
        Map<String, Object> params = page(jsonObject);
        List<DeptEducationContent> list = wxApletService.selectByPrimaryKey21(params);
        if (list.size() > 0) {
            return new ResultModel<Object>(list.get(0));
        }
        return new ResultModel<Object>("{}");
    }

    //22
    @ResponseBody
    @RequestMapping(value = "/selectByPrimaryKey22")
    public ResultModel selectByPrimaryKey22(@RequestBody String requestBody) {
        log.info("22-->" + requestBody);
        JSONObject jsonObject = JSON.parseObject(requestBody);
        jsonObject = jsonObject.getJSONObject("data");
        if (jsonObject.isEmpty()) {
            return new ResultModel<Object>("查询数据错误");
        }
        Map<String, Object> params = page(jsonObject);
        List<DeptEducationTemplate> list = wxApletService.selectByPrimaryKey22(params);
        if (list.size() > 0) {
            return new ResultModel<Object>(list.get(0));
        }
        return new ResultModel<Object>("{}");
    }

    /**
     * Edit by jiangq on 2022年05月17日
     * NBNA报告页获取
     *
     * @param requestBody
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getNbnaReport")
    public ResultModel<Object> getNbnaReport(@RequestBody String requestBody, HttpServletRequest request) throws Exception {
        JSONObject jsonObject = JSON.parseObject(requestBody);
        jsonObject = jsonObject.getJSONObject("data");
        if (jsonObject.isEmpty()) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "查询数据错误");
        }
        Map<String, Object> params = page(jsonObject);

        String userId = (String) params.get("userId");
        if (StringUtils.isEmpty(userId)) {
            log.info("out getHistoryScore----arg== null");
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，患者ID不能为空");
        }

        String type = (String) params.get("examinationPaperName");
        if (StringUtils.isEmpty(type)) {
            log.info("out getHistoryScore----arg== null");
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，随访评测类型不能为空");
        }

        List<String> typeList = new ArrayList<String>();
        typeList.add(type);

        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.putAll(params);
        paramMap.put("userId", userId);
        paramMap.put("typeList", typeList);

        //查询租户id
        Patient patient = patientService.getPatient(paramMap);
        paramMap.put("tenantId", patient.getTenantId());

        List<Map<String, Object>> list = followEvaluationService.selectPtEvaluationResults(paramMap);
        //int total= 0;
        //if(!CollectionUtils.isEmpty(list)){
        //    total= followEvaluationService.selectPtEvaluationResultCount(paramMap);
        //}
        log.info("out getHistoryScore----arg==" + list);
        return new ResultModel<Object>(list);
    }

    @RequestMapping("/getGuide")
    @ResponseBody
    public ResultModel<Map<String, Object>> getGuide(@RequestBody String arg, HttpServletRequest request) throws Exception {
        log.info("in getGuide----arg==" + arg);

        JSONObject jsonEsb = JSON.parseObject(arg);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

        Map<String, Object> params = page(requestParam);
        String examinationPaperName = (String) params.get("examinationPaperName");
        if (StringUtils.isEmpty(examinationPaperName)) {
            log.info("out getGuide----arg== null");
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，examinationPaperName不能为空");
        }

        String userId = (String) params.get("userId");
        if (StringUtils.isEmpty(userId)) {
            log.info("out getGuide----arg== null");
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，患者id不能为空");
        }

        Map<String, Object> ptMap = new HashMap<String, Object>();
        ptMap.put("userId", userId);
        //ptMap.put("tenantId",tenantId);
        Patient pt = patientService.getPatient(ptMap);
        if (pt == null) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST, "患者信息不存在");
        }

        Map<String, Object> paramsMap = new HashMap<String, Object>();
//		String postion="";
        if (pt.getBirthday() != null) {
            Date birthday = DateUtil.getDate_8(pt.getBirthday());
            if (Constants.FOLLOW_EVALUATION_NEUR.equals(examinationPaperName)) {

            } else if (Constants.FOLLOW_EVALUATION_BAILEY.equals(examinationPaperName)) {
                paramsMap = followEvaluationService.getBaileyScreeningGuide(birthday);
            } else if (Constants.FOLLOW_EVALUATION_GESELL.equals(examinationPaperName)) {
                Map<String, Object> param = new HashMap<String, Object>();
                if (StringUtils.isBlank((String) params.get("evaluationId"))) {
                    throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST, "记录id");
                } else {
                    param.put("evaluationId", params.get("evaluationId"));
                }
                param.put("createTime", params.get("createTime"));
                paramsMap = followEvaluationService.getGesellGuide(param, pt);
            } else if (Constants.FOLLOW_EVALUATION_TEMP.equals(examinationPaperName)) {
                Map<String, Object> param = new HashMap<String, Object>();
                param.put("type", params.get("type"));
                paramsMap = followEvaluationService.getTEMPGuide(param, pt);

            } else if (Constants.FOLLOW_EVALUATION_SMALlWECHSLER.equals(examinationPaperName)) {
            } else if (Constants.FOLLOW_EVALUATION_BIGWECHSLER.equals(examinationPaperName)) {
            } else if (Constants.FOLLOW_EVALUATION_PREGNANT_AIMS.equals(examinationPaperName) || Constants.FOLLOW_EVALUATION_PREGNANT_PEABODY.equals(examinationPaperName) ||
                    Constants.FOLLOW_EVALUATION_PREGNANT_BSID2.equals(examinationPaperName) || Constants.FOLLOW_EVALUATION_NBNA.equals(examinationPaperName) ||
                    Constants.FOLLOW_EVALUATION_GROWTH.equals(examinationPaperName) || Constants.FOLLOW_EVALUATION_PREGNANT_GMS.equals(examinationPaperName)) {
                //aims评估结果意见 从表查询
                Map<String, Object> param = new HashMap<String, Object>();
                if (Constants.FOLLOW_EVALUATION_GROWTH.equals(params.get("examinationPaperName"))) {
                    param.put("type", params.get("examinationPaperName"));
                }
                param.put("evaluationId", params.get("evaluationId"));
                paramsMap = followEvaluationService.getEvaluationGuide(param);
            } else if (Constants.FOLLOW_EVALUATION_PREGNANT_BSID.equals(examinationPaperName)) {
                Map<String, Object> param = new HashMap<String, Object>();
                if (StringUtils.isBlank((String) params.get("age"))) {
                    throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST, "年龄必传！");
                }
                param.put("age", params.get("age"));
                paramsMap = followEvaluationService.getEvaluationGuideByAge(param);
            }
        }
        return new ResultModel<Map<String, Object>>(paramsMap);
    }

    private Map page(JSONObject jsonObject) {
        JSONObject jsonData = jsonObject.getJSONObject("params");

        Map<String, Object> params = new HashMap<String, Object>();
        Iterator ite = jsonData.keySet().iterator();
        // 遍历jsonObject数据,添加到Map对象
        while (ite.hasNext()) {
            String key = ite.next().toString();
            String value = jsonData.get(key).toString();
            params.put(key, value);
        }
        if (params.containsKey("pageIndex")) {
            int x = Integer.parseInt(params.get("pageIndex").toString());
            int y = Integer.parseInt(params.get("pageSize").toString());
            params.put("pageIndex", x);
            params.put("pageSize", y);
            params.put("page", (x - 1) * y);
        } else {
            params.put("page", null);
        }
        return params;
    }

    /**
     * Edit by jiangq on 2022年06月27日
     * 小程序远程建档调用
     *
     * @param receiveMsg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/xcxAddNewPatient")
    public ResultModel<Object> xcxAddNewPatient(@RequestBody String receiveMsg, HttpServletRequest request) throws Exception {
        JSONObject jsonEsb = JSON.parseObject(receiveMsg);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

        Map<String, Object> jsonArg = page(requestParam);

        String sendMsg = null;

        // 小程序消息队列传入的type，判断是2.0建档还是3.0建档
        // 1作为2.0建档，3作为3.0建档
        // 8作为2.0随访门诊预约类型
        Integer type = Integer.parseInt(jsonArg.get("type").toString());
        // code判断是否为发送消息
        String code = (String) jsonArg.get("code");
        if (type == 1 && code == null) {

            // 获取问卷内容
            Map<String, Object> quesMap = new HashMap<String, Object>();
            quesMap = (Map<String, Object>) JSON.parse(jsonArg.get("content").toString());

            String userId = (String) jsonArg.get("userId");
            String userIdNew = "";
            String queueId = (String) jsonArg.get("queueId");
            Map<String, Object> map = new HashMap<String, Object>();
            Map<String, Object> chkMapIn = new HashMap<String, Object>();
            boolean isVerify = true;
            map.put("id", queueId);
            chkMapIn.put("queueId", queueId);
            FollowQueue queue = followQueueSerivce.getQueueDetailByQueueId(map);
            if (null == queue) {
                sendMsg = "{\"type\":" + type + ",\"code\":\"" + ErrorCode.FOLLOWUP_EXCEPTION_TYPE_QUEUE_NOT_EXIST + "\",\"msg\":\"根据队列id查询无此队列信息！\",\"userId\":\"" + userId + "\"}";
                return new ResultModel<Object>(sendMsg);
                //throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_QUEUE_NOT_EXIST, "根据队列id查询无此队列信息！"));
            }

            String queueUserType = queue.getQueueUsertype();

            Map<String, Object> servParamMap = new HashMap<String, Object>();

            String author = "小程序建档";
            String authorName = "同步小程序建档";
            String tenantId = queue.getTenantId();
            String deptId = queue.getDeptId();

            // 操作编码默认：1000（患者建档）
            String opCode = "1000";
            // 操作类型默认：2（门诊）
            String opType = "2";
            // 患者来源渠道默认：9（小程序建档）
            String sourceType = Constants.PATIENT_SOURCE_TYPE_MINI_PROGRAM;
            String opNote = "小程序建档";
            // 创建时间
            String currTime = DateUtil.getTimeString(DateUtil.getSysDateA());

            String userType = null;
            if (Constants.QUEUE_USER_TYPE_BABY.equals(queueUserType)) {
                // 宝宝
                userType = "1";
                servParamMap.put("userType", userType);
            } else if (Constants.QUEUE_USER_TYPE_PARTURIENT.equals(queueUserType)) {
                // 孕产妇
                userType = "2";
                servParamMap.put("userType", userType);
            } else if (Constants.QUEUE_USER_TYPE_OTHER.equals(queueUserType)) {
                // 其他
                userType = "3";
                servParamMap.put("userType", userType);
            }

            Map<String, Object> userMap = new HashMap<>();

            String updateAccept = SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_SYSTEMID);// 操作流水

            String phoneNum = null;
            if (StringUtils.isBlank(phoneNum)) {
                if (null != quesMap && 0 != quesMap.size()) {
                    phoneNum = (String) quesMap.get(Constants.QUESTION_ID_FOR_PHONENO);
                }
            }
            if (StringUtils.isBlank(phoneNum)) {
                phoneNum = "";
                chkMapIn.put("quesId", Constants.QUESTION_ID_FOR_PHONENO);
                isVerify = patientArchService.isVerifyArchiveParam(chkMapIn);
                if (isVerify) {
                    sendMsg = "{\"type\":" + type + ",\"code\":\"" + ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR + "\",\"msg\":\"手机号码不能为空！\",\"userId\":\"" + userId + "\"}";
                    return new ResultModel<Object>(sendMsg);
                    //throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "手机号码不能为空！"));
                }
            }
            phoneNum = phoneNum.trim();

            String patientName = null;
            if (StringUtils.isBlank(patientName)) {
                if (null != quesMap && 0 != quesMap.size()) {
                    patientName = (String) quesMap.get(Constants.QUESTION_ID_FOR_PATIENTNAME);
                }
            }
            if (StringUtils.isBlank(patientName)) {
                patientName = "";
                chkMapIn.put("quesId", Constants.QUESTION_ID_FOR_PATIENTNAME);
                isVerify = patientArchService.isVerifyArchiveParam(chkMapIn);
                if (isVerify) {
                    sendMsg = "{\"type\":" + type + ",\"code\":\"" + ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR + "\",\"msg\":\"患者姓名不能为空！\",\"userId\":\"" + userId + "\"}";
                    return new ResultModel<Object>(sendMsg);
                    //throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "患者姓名不能为空！"));
                }
            }
            patientName = patientName.trim();

            String gender = null;
            if (Constants.QUEUE_USER_TYPE_PARTURIENT.equals(queueUserType)) {
                // 孕产妇（母亲）
                gender = Constants.GENDER_FOR_FEMALE;
            } else if (StringUtils.isBlank(gender)) {
                if (null != quesMap && 0 != quesMap.size()) {
                    gender = (String) quesMap.get(Constants.QUESTION_ID_FOR_GENDER);
                }
            }
            if (StringUtils.isBlank(gender)) {
                gender = "";
                chkMapIn.put("quesId", Constants.QUESTION_ID_FOR_GENDER);
                isVerify = patientArchService.isVerifyArchiveParam(chkMapIn);
                if (isVerify) {
                    sendMsg = "{\"type\":" + type + ",\"code\":\"" + ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR + "\",\"msg\":\"性别不能为空！\",\"userId\":\"" + userId + "\"}";
                    return new ResultModel<Object>(sendMsg);
                    //throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "性别不能为空！"));
                }
            }
            gender = gender.trim();
            // 转换性别
            if (Constants.GENDER_ALIAS_FOR_MALE.equals(gender)) {
                gender = Constants.GENDER_FOR_MALE;
            } else if (Constants.GENDER_ALIAS_FOR_FEMALE.equals(gender)) {
                gender = Constants.GENDER_FOR_FEMALE;
            } else if (!Constants.GENDER_FOR_MALE.equals(gender) && !Constants.GENDER_FOR_FEMALE.equals(gender)) {
                gender = Constants.GENDER_FOR_MALE;
            }

            String birthday = null;
            if (StringUtils.isBlank(birthday)) {
                if (null != quesMap && 0 != quesMap.size()) {
                    birthday = (String) quesMap.get(Constants.QUESTION_ID_FOR_BIRTHDAY);
                    // Excel获取年龄格式为yyyy-MM-dd HH:mm:ss处理成yyyy-MM-dd格式，方便后续时间节点计算
                    String[] birthdays = birthday.split(" ");
                    birthday = birthdays[0];
                }
            }
            if (StringUtils.isBlank(birthday) && !Constants.QUEUE_USER_TYPE_PARTURIENT.equals(queueUserType)) {
                birthday = null;
                chkMapIn.put("quesId", Constants.QUESTION_ID_FOR_BIRTHDAY);
                isVerify = patientArchService.isVerifyArchiveParam(chkMapIn);
                if (isVerify) {
                    sendMsg = "{\"type\":" + type + ",\"code\":\"" + ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR + "\",\"msg\":\"出生日期不能为空！\",\"userId\":\"" + userId + "\"}";
                    return new ResultModel<Object>(sendMsg);
                    //throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "出生日期不能为空！"));
                }
            }

            // 预产期
            String expectedDay = null;
            if (StringUtils.isBlank(expectedDay)) {
                if (null != quesMap && 0 != quesMap.size()) {
                    expectedDay = (String) quesMap.get(Constants.QUESTION_ID_FOR_EXPECTEDDAY);
                }
            }
            if (StringUtils.isEmpty(expectedDay)) {
                expectedDay = null;
            }

            // 出生胎龄(孕周)
            int pregnancyDay = 0;
            // 再考虑从问卷中获取，问卷存储格式天
            if (pregnancyDay <= 0 && !MapUtils.isEmpty(quesMap)) {
                pregnancyDay = Integer.parseInt((String) quesMap.get(Constants.QUESTION_ID_FOR_PREGNANCYDAY));
//                                String preStr = (String) quesMap.get(Constants.QUESTION_ID_FOR_PREGNANCYDAY);
//                                if (!StringUtils.isBlank(preStr)) {
//                                    String preArr[] = preStr.split(Constants.COMMA_SPLIT_STR);
//                                    if (null != preArr && 2 == preArr.length) {
//                                        String preWeekStr = preArr[0].substring(1);
//                                        String preDayStr = preArr[1].substring(0, preArr[1].length() - 1);
//                                        int preWeek = Integer.parseInt(preWeekStr);
//                                        int preDay = Integer.parseInt(preDayStr);
//                                        pregnancyDay = preWeek * Constants.PREGNANCY_CALC_UNIT_WEEK + preDay;
//                                    }
//                                }
            }
            // 最后根据根据生日和预产期计算
            if (Constants.QUEUE_USER_TYPE_PARTURIENT.equals(queueUserType)) {
                // 孕产妇（母亲）
                // 初检孕周
                String firstChkPregWeek = (String) quesMap.get(Constants.QUESTION_ID_FOR_PREGNANCY_FIRST_WEEK);
                if (StringUtils.isBlank(firstChkPregWeek)) {
                    // 不在这里校验，在实例化随访任务时校验
                } else {
                    servParamMap.put("firstChkPregWeek", Integer.parseInt(firstChkPregWeek));
                }
                // 末次月经日期
                String lastMenstruationDate = (String) quesMap.get(Constants.QUESTION_ID_FOR_LAST_MENSTRUATION_DATE);
                if (StringUtils.isBlank(lastMenstruationDate)) {
                    // 不在这里校验，在实例化随访任务时校验
                } else {
                    servParamMap.put("lastMenstruationDate", lastMenstruationDate);
                }
                // 分娩日期
                servParamMap.put("deliveryDate", quesMap.get(Constants.QUESTION_ID_FOR_LAST_DELIVERY_DATE));
            } else if (pregnancyDay <= 0 && !StringUtils.isBlank(expectedDay)) {
                pregnancyDay = ToolUtils.calPrenDayByBirthAndExpect(birthday, expectedDay);
            }

            // 孕周未填，默认280
            if (pregnancyDay <= 0) {
                pregnancyDay = Constants.PATIENT_NORMAL_PREGNANT_DAY;
            }
            // 预产期未填，默认与出生日期一致
            if (StringUtils.isBlank(expectedDay)) {
                expectedDay = birthday;
            }

            if (pregnancyDay > 321) {
                sendMsg = "{\"type\":" + type + ",\"code\":\"" + ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR + "\",\"msg\":\"出生日期或者预产期不正确，请检查！\",\"userId\":\"" + userId + "\"}";
                return new ResultModel<Object>(sendMsg);
                //throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"尊敬的用户，您填写的出生日期或者预产期不正确，请检查！");
            }

            // 防止重复新建患者
            Map<String, Object> qryPtMap = new HashMap<String, Object>();
            qryPtMap.put("phoneNo", phoneNum);
            qryPtMap.put("userName", patientName);
            qryPtMap.put("tenantId", tenantId);
            // 不同类型用户
            qryPtMap.put("userType", userType);
            List<Patient> ptList = iPatientDAO.selectByPhoneNo(qryPtMap);
            List<PatientQueueScheme> pqsList = new ArrayList<PatientQueueScheme>();
            if (!org.springframework.util.CollectionUtils.isEmpty(ptList)) {
                // 校验患者是否已经加入过该队列
                HashMap<String, Object> qryPqsMap = new HashMap<String, Object>();
                qryPqsMap.put("userId", ptList.get(0).getId());
                qryPqsMap.put("queueId", queueId);

                List<String> statulist = new ArrayList<String>();

                statulist.add(Constants.PATIENT_QUEUESCHEME_USER_STATUS_NOMAL);

                qryPqsMap.put("status", statulist);

                pqsList = iPatientQueueSchemeDAO.selectByUserId(qryPqsMap);
            }

            if (org.springframework.util.CollectionUtils.isEmpty(pqsList)) {
                Patient pt = new Patient();

                pt.setPregnancyDay(pregnancyDay);
                pt.setUserName(patientName);
                pt.setPhoneNo(phoneNum);
                pt.setFirstName(patientName.substring(0, 1));
                pt.setCreateTime(currTime);
                pt.setUpdateTime(currTime);
                pt.setCreateAuthor(author);
                pt.setBirthday(birthday);
                pt.setExpectedDay(expectedDay);
                pt.setGender(gender);
                pt.setUserType(userType);
                pt.setSourceType(sourceType);

                try {
                    servParamMap.put("patient", pt);
                    servParamMap.put("authorName", authorName);
                    servParamMap.put("deptId", deptId);
                    servParamMap.put("queueId", queueId);
                    servParamMap.put("updateTime", currTime);
                    servParamMap.put("authorId", author);
                    servParamMap.put("updateAccept", updateAccept);
                    servParamMap.put("tenantId", tenantId);
                    servParamMap.put("opCode", opCode);
                    servParamMap.put("opNote", opNote);
                    servParamMap.put("opType", opType);
                    servParamMap.put("contentData", quesMap);
                    userMap = patientSerivce.registerPatient(servParamMap);
                    userIdNew = (String) userMap.get("patientId");
                    if (StringUtils.isNotEmpty(userIdNew)) {
                        //模拟登录获取sessionId
                        RestTemplate restTemplate = new RestTemplate();
                        String username = "19912341011";
                        String password = "123456";
                        String loginUrl = PropertiesUtils.getProperty("loginUrl") + "?username=" + username + "&password=" + password;
                        ResponseEntity<String> resEntity = restTemplate.postForEntity(loginUrl, null, String.class);
                        String sessionID = (String) JSONObject.parseObject(resEntity.getBody()).getJSONObject("data").get("sessionID");
                        log.info("sessionID=================" + sessionID);
                        //获取需要推送的量表id
                        String ptBirthday = pt.getBirthday();
                        String getPaperIdsUrl = PropertiesUtils.getProperty("getPaperIdsUrl") + "?sessionId=" + sessionID + "&birthday=" + ptBirthday;
                        ResponseEntity<String> resPaperIds = restTemplate.postForEntity(getPaperIdsUrl, null, String.class);
                        String body1 = resPaperIds.getBody();
                        String paperIds = JSONObject.parseObject(body1).get("paperIds").toString();
                        log.info(paperIds);
                        if (StringUtils.isNotEmpty(paperIds)) {
                            //推送线上测评固定量表
                            HashMap<String, Object> nirnParamMap = new HashMap<>();
                            nirnParamMap.put("queueId", queueId);
                            nirnParamMap.put("patientId", pt.getId());
                            nirnParamMap.put("patientName", pt.getUserName());
                            nirnParamMap.put("gender", pt.getGender().equals("N") ? 1 : 2);
                            nirnParamMap.put("birthday", pt.getBirthday());
                            nirnParamMap.put("phoneNum", pt.getPhoneNo());

                            String getPatientIdUrl = PropertiesUtils.getProperty("getPatientIdUrl") + "?sessionId=" + sessionID;
                            log.info("getPatientIdUrl=====================" + getPatientIdUrl);
                            RestTemplate restTemplate1 = new RestTemplate();
                            HttpHeaders headers = new HttpHeaders();
                            headers.setContentType(MediaType.APPLICATION_JSON);
                            HttpEntity<HashMap<String, Object>> httpPatientEntity = new HttpEntity<>(nirnParamMap, headers);
                            log.info("httpPatientEntity====================" + httpPatientEntity);
                            ResponseEntity<String> resNirn = restTemplate1.postForEntity(getPatientIdUrl, httpPatientEntity, String.class);
                            log.info("resNirn===================" + resNirn);
                            String body = resNirn.getBody();
                            String patientId = JSONObject.parseObject(body).get("id").toString();
                            log.info("patientId===================" + patientId);

                            String pushNirnUrl = PropertiesUtils.getProperty("pushNirnUrl") + "?sessionId=" + sessionID;
                            HashMap<String, Object> nirnPushParamMap = new HashMap<>();
                            nirnPushParamMap.put("paperIds", paperIds);
                            nirnPushParamMap.put("patientId", patientId);
                            nirnPushParamMap.put("scheduleId", null);
                            HttpEntity<HashMap<String, Object>> httpSaveEntity = new HttpEntity<>(nirnPushParamMap, headers);
                            ResponseEntity<HashMap> responseSaveRes = restTemplate1.postForEntity(pushNirnUrl, httpSaveEntity, HashMap.class);
                            log.info("responseSaveRes================" + responseSaveRes);
                        }
                    }

                    quesMap.clear();
                } catch (RestClientException e) {
                    //sendMsg = "{\"type\":" + type + ",\"code\":\"" + ErrorCode.SMALL_PROGRAM_SCALEPUSH_FAILURE + "\",\"msg\":\"推送量表失败！\",\"userId\":\"" + userId + "\"}";
                    //return new ResultModel<Object>(sendMsg);
                    String platType = departmentBasicService.getDepartmentBasicDetails(deptId).getPlatType();
                    sendMsg = "{\"type\":" + type + ",\"deptId\":\"" + deptId + "\",\"code\":\"0\",\"msg\":\"同步建档成功！\",\"userId\":\"" + userIdNew + "\",\"tenantId\":\"" + tenantId + "\",\"platType\":" +
                            platType + ",\"oriUserId\":\"" + userId + "\"}";
                    System.out.println("============================================================ 患者建档成功");
                    return new ResultModel<Object>(sendMsg);
                } catch (Exception e) {
                    sendMsg = "{\"type\":" + type + ",\"code\":\"" + ErrorCode.SMALL_PROGRAM_EXCEPTION_ARCHIVE_FAILURE + "\",\"msg\":\"同步建档失败！\",\"userId\":\"" + userId + "\"}";
                    return new ResultModel<Object>(sendMsg);
                    //throw new AppException(ErrorCode.SMALL_PROGRAM_EXCEPTION_ARCHIVE_FAILURE, "同步建档失败！");
                }
            } else {
                sendMsg = "{\"type\":" + type + ",\"code\":\"" + ErrorCode.SMALL_PROGRAM_EXCEPTION_ARCHIVE_FAILURE + "\",\"msg\":\"该类型用户在该队列下已建过档，不能重复建档！\",\"userId\":\"" + userId + "\"}";
                return new ResultModel<Object>(sendMsg);
            }

            if (!userMap.isEmpty()) {
                String platType = departmentBasicService.getDepartmentBasicDetails(deptId).getPlatType();
                sendMsg = "{\"type\":" + type + ",\"deptId\":\"" + deptId + "\",\"code\":\"0\",\"msg\":\"同步建档成功！\",\"userId\":\"" + userIdNew + "\",\"tenantId\":\"" + tenantId + "\",\"platType\":" +
                        platType + ",\"oriUserId\":\"" + userId + "\"}";
                System.out.println("============================================================ 患者建档成功");
                return new ResultModel<Object>(sendMsg);
            }
        }


        return new ResultModel<Object>(null);
    }

    @ResponseBody
    @RequestMapping("/updateArchiveInfo")
    public ResultModel<String> updateArchiveInfo(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        log.warn("in updateArchiveInfo----arg==" + arg.toString());
        JSONObject jsonEsb = JSON.parseObject(arg);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
        log.warn("in updateArchiveInfo----requestParam==" + requestParam.toString());
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

        Map<String, Object> jsonArg = page(requestParam);
        log.warn("in updateArchiveInfo----jsonArg==" + jsonArg.toString());
        Map<String, String> quesMap = new HashMap<String, String>();
        String jsonStr = (String) jsonArg.get("content");
        quesMap = JSON.parseObject(jsonStr, new TypeReference<HashMap<String, String>>() {
        });
        //quesMap = (Map<String, Object>) jsonArg.get("content");
        //更新建档的信息
        Map<String, Object> userMapIn = new HashMap<String, Object>();
        userMapIn.put("userId", jsonArg.get("userId"));
        userMapIn.put("tenantId", jsonArg.get("tenantId"));
        userMapIn.put("updateTime", new Date());
        HashMap<String, Object> updateParam = MapUtil.newHashMap();
        for (Map.Entry<String, String> entry : quesMap.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue().toString().trim();
            // 手机号码
            if (key.equals(Constants.QUESTION_ID_FOR_PHONENO)) {
                if (!StringUtils.isBlank(value.toString())) {
                    userMapIn.put("phoneNo", value);
                }
            }
            // 患者姓名
            if (key.equals(Constants.QUESTION_ID_FOR_PATIENTNAME)) {
                if (!StringUtils.isBlank(value)) {
                    userMapIn.put("userName", value);
                }
                //更新名字拼音 2018-01-11
                try {
                    userMapIn.put("namePinyin", ToolUtil.getEname(value));
                    userMapIn.put("nameInitial", ToolUtil.getNameInitial(value));
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    userMapIn.put("namePinyin", null);
                    userMapIn.put("nameInitial", null);
                }
                userMapIn.put("firstName", value.substring(0, 1));
            }
            // 性别
            if (key.equals(Constants.QUESTION_ID_FOR_GENDER)) {
                if (!StringUtils.isBlank(value)) {
                    // 转换性别
                    if (Constants.GENDER_ALIAS_FOR_MALE.equals(value) || value.startsWith(Constants.GENDER_ALIAS_FOR_MALE)) {
                        value = Constants.GENDER_FOR_MALE;
                    } else if (Constants.GENDER_ALIAS_FOR_FEMALE.equals(value) || value.startsWith(Constants.GENDER_ALIAS_FOR_FEMALE)) {
                        value = Constants.GENDER_FOR_FEMALE;
                    } else if (!Constants.GENDER_FOR_MALE.equals(value) && !Constants.GENDER_FOR_FEMALE.equals(value)) {
                        value = Constants.GENDER_FOR_MALE;
                    }
                    userMapIn.put("gender", value);
                }
            }
            // 出生日期
            if (key.equals(Constants.QUESTION_ID_FOR_BIRTHDAY)) {
                if (!StringUtils.isBlank(value)) {
                    userMapIn.put("birthday", value);
                }
            }
            // 预产期
            if (key.equals(Constants.QUESTION_ID_FOR_EXPECTEDDAY)) {
                if (!StringUtils.isBlank(value)) {
                    userMapIn.put("expectedDay", value);
                }
            }
            if (key.equals(Constants.QUESTION_ID_FOR_IDCARD)) {
                if (!StringUtils.isBlank(value)) {
                    userMapIn.put("idCard", value);
                }
            }
            if (key.equals(Constants.QUESTION_ID_FOR_PREGNANCYDAY)) {
                if (!StringUtils.isBlank(value)) {
                    userMapIn.put("pregnancyDay", value);
                }
            }
            if (key.equals(Constants.QUESTION_ID_FOR_INPATIENT_NO)) {
                if (!StringUtils.isBlank(value)) {
                    userMapIn.put("hospitalNo", value);
                }
            }
            updateParam.put("questionAnswer", entry.getValue());
            updateParam.put("questionId", entry.getKey());
            updateParam.put("tenantId", jsonArg.get("tenantId"));
            updateParam.put("userId", jsonArg.get("userId"));
            patientTaskContentDAO.updateAnswerByTenantIdAndUserIdAndQuestionId(updateParam);
        }
        //以下为需要新增题目
        iPatientDAO.updatePatientInfoById(userMapIn);
        String saveListString = (String) jsonArg.get("saveList");
        List<PatientContentData> saveList = JSONArray.parseArray(saveListString, PatientContentData.class);
        if (saveList.size() > 0) {
            for (PatientContentData patientContentData : saveList) {
                if (patientContentData.getCreateTime() == null) {
                    patientContentData.setCreateTime(DateUtil.getSysDateA());
                }
                if (patientContentData.getUpdateTime() == null) {
                    patientContentData.setUpdateTime(DateUtil.getSysDateA());
                }
            }
            patientTaskContentDAO.savePatientTaskContentDataBatch(saveList);
        }
        return new ResultModel<String>("");
    }

    @ResponseBody
    @RequestMapping("/selectBySchemeVersionid")
    public ResultModel<Object> selectBySchemeVersionid(@RequestBody String arg, HttpServletRequest request) throws Exception {
        log.warn("in selectBySchemeVersionid----arg==" + arg.toString());
        JSONObject jsonObject = JSON.parseObject(arg);
        jsonObject = jsonObject.getJSONObject("data");
        if (jsonObject.isEmpty()) {
            return new ResultModel<Object>("查询数据错误");
        }
        Map<String, Object> params = page(jsonObject);
        List<FollowTask> result = followTaskDAO.selectBySchemeVersionid(params);
        return new ResultModel<Object>(result);
    }

    @ResponseBody
    @RequestMapping("/patientTaskContentDataQuery")
    public ResultModel patientTaskContentDataQuery(@RequestBody String arg, HttpServletRequest request) throws Exception {
        log.warn("in patientTaskContentDataQuery----arg==" + arg.toString());
        JSONObject jsonObject = JSON.parseObject(arg);
        jsonObject = jsonObject.getJSONObject("data");
        if (jsonObject.isEmpty()) {
            return new ResultModel<Object>("查询数据错误");
        }
        Map<String, Object> params = page(jsonObject);


        String taskId = (String) params.get("ptTaskId");
        if (null == taskId || "".equals(taskId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
                    "入参节点错误，未传入患者任务id或值为空！"));
        }
        String queueId = (String) params.get("followQueueId");
        if (null == queueId || "".equals(queueId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，未传入队列id或值为空！"));
        }

        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("taskId", taskId);
        paramMap.put("queueId", queueId);
        HashMap<String, Object> retMap = patientSerivce.qryOnlinePatientContentList(paramMap);

        return new ResultModel<Object>(retMap);
    }

    // 患者任务内容更新
    @ResponseBody
    @RequestMapping("/patientTaskContentDataModify")
    public ResultModel<Object> savePatientContentInfo(@RequestBody String arg,
                                                      HttpServletRequest request) throws Exception {
        log.warn("in savePatientContentInfo----arg==" + arg);
        JSONObject jsonObject = JSON.parseObject(arg);
        jsonObject = jsonObject.getJSONObject("data");
        if (jsonObject.isEmpty()) {
            return new ResultModel<Object>("查询数据错误");
        }
        Map<String, Object> params = page(jsonObject);
        JSONObject jsonData = new JSONObject(params);

        String deptId = (String) params.get("deptId");
        String tenantId = (String) params.get("tenantId");

        JSONObject jsonTask = (JSONObject) jsonData.getJSONObject("task");
        if (null == jsonTask) {
            // 前台必须传task节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无task节点！"));
        }
        JSONObject jsonOpInfo = (JSONObject) jsonData.getJSONObject("oprInfo");
        if (null == jsonOpInfo) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无oprInfo节点！"));
        }
        String opCode = (String) jsonOpInfo.get("opCode");
        if (null == opCode || "".equals(opCode)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无操作编码节点！"));
        }
        String queueId = (String) jsonOpInfo.get("followQueueId");
        if (null == queueId || "".equals(queueId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无队列id节点！"));
        }
        String ptSchemeId = (String) jsonOpInfo.get("ptSchemeId");
        if (null == ptSchemeId || "".equals(ptSchemeId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
                    "入参节点错误，未传入患者队列实例id或值为空！"));
        }
        String userId = (String) jsonOpInfo.get("patientId");
        if (null == userId || "".equals(userId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，患者id未传或值为空！"));
        }

        // 入参中没有，从问卷答案中获取
        Map<String, Object> quesMap = (JSONObject) jsonData.getJSONObject("questiones");
        HashMap<String, Object> paramMap = new HashMap<String, Object>();

        // 修改手机号同步app 使用ptTaskInfoSelectBySearchVoUri
        paramMap.put("deptId", deptId);

        String taskId = jsonTask.getString("ptTaskId");
        if (null == taskId || "".equals(taskId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
                    "入参节点错误，未传入患者任务id或值为空！"));
        }
        String seqNo = jsonTask.getString("seqNo");
        boolean initTask = false;// 建档任务
        if (!StringUtils.isEmpty(seqNo)) {
            if (seqNo.equals("" + Constants.TASK_SEQ_FOR_INIT)) {
                initTask = true;
            }
        }

        String finishDate = jsonTask.getString("finishDate");
        if (!initTask && StringUtils.isBlank(finishDate)) {
            // 建档可以不传随访日期
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "未传入随访日期或值为空！"));
        }
        String updateAuname = jsonTask.getString("updateAuname");
        if (StringUtils.isBlank(updateAuname)) {
            updateAuname = "用户线上修改";
        }

        JSONArray ptContentIds = jsonTask.getJSONArray("ptContentIds");
        if (null == ptContentIds || 0 == ptContentIds.size()) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
                    "入参节点错误，未传入患者任务内容id节点或值为空！"));
        }
        Object contentData = params.get("questiones");
        if (null == contentData || "".equals(contentData)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
                    "入参节点错误，未传入任务内容报文或值为空！"));
        }
        // 生物样本采集信息（安医大需求）
        JSONArray sampleList = (JSONArray) params.get("sampleList");
        if (null != sampleList) {
            paramMap.put("sampleList", sampleList);
        }

        String currTime = jsonOpInfo.getString("opTime");// 入参中有操作时间，则使用入参中的时间
        if (StringUtils.isBlank(currTime)) {
            currTime = DateUtil.getTimeString(DateUtil.getSysDateA());// 创建时间
        }

        String taskNote = jsonTask.getString("taskNote");
        if (StringUtils.isBlank(taskNote)) {
            if (null != quesMap && 0 != quesMap.size()) {
                taskNote = (String) quesMap.get(Constants.QUESTION_ID_FOR_TR_TASK_FOLLOW_NOTE);
            }
        }

        String nextDate = jsonTask.getString("nextDate");
        if (StringUtils.isBlank(nextDate)) {
            if (null != quesMap && 0 != quesMap.size()) {
                nextDate = (String) quesMap.get(Constants.QUESTION_ID_FOR_TR_TASK_FOLLOW_DATE);
            }
        }

        String nextAddress = jsonTask.getString("nextAddress");
        if (StringUtils.isBlank(nextAddress)) {
            if (null != quesMap && 0 != quesMap.size()) {
                nextAddress = (String) quesMap.get(Constants.QUESTION_ID_FOR_TR_TASK_FOLLOW_ADDRESS);
            }
        }
        // 来源渠道
        String sourceType = jsonOpInfo.getString("sourceType");
        if (StringUtils.isBlank(sourceType)) {
            // 默认小程序门诊渠道
            sourceType = Constants.PATIENT_SOURCE_TYPE_MINI_PROGRAM;
        }
        paramMap.put("sourceType", sourceType);

        String updateAccept = SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_SYSTEMID);// 操作流水
        paramMap.put("taskId", taskId);
        paramMap.put("contentData", params.get("questiones"));
        paramMap.put("ptSchemeId", ptSchemeId);
        paramMap.put("userId", userId);
        paramMap.put("updateTime", currTime);
        paramMap.put("updateAccept", updateAccept);
        paramMap.put("authorId", "999");//线上问卷修改默认为999
        paramMap.put("tenantId", tenantId);
        paramMap.put("opCode", opCode);
        paramMap.put("queueId", queueId);
        paramMap.put("opNote", jsonOpInfo.getString("opNote"));
        paramMap.put("opType", jsonOpInfo.getString("opType"));
        paramMap.put("ptContentIds", ptContentIds);
        paramMap.put("updateAuname", updateAuname);
        paramMap.put("finishDate", finishDate);
        paramMap.put("taskNote", taskNote);
        paramMap.put("nextDate", nextDate);
        paramMap.put("nextAddress", nextAddress);

        // 问卷类型，这里先写死0代表门诊问卷
        paramMap.put("type", Constants.QUESTIONNAIRE_TYPE_9);
        patientSerivce.modTaskContentData(paramMap);

        String sendMsg = null;

        if (("0").equals(seqNo)) {

            //修改用户下所有手机号
            String phone = quesMap.get("Pub1100001").toString();
            patientPhoneService.updatePatientPhone(tenantId, userId, phone, "999");
            // type=12 患者修改信息推送
            int type = Constants.UPDATE_USER;
            // system=1 2.0系统
            int system = 1;
            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("type", type);
            jsonObject1.put("userId", userId);
            jsonObject1.put("tenantId", tenantId);
            jsonObject1.put("system", system);
            jsonObject1.put("deptId", deptId);
            sendMsg = jsonObject.toJSONString();
            if (StringUtils.isNotBlank(PropertiesUtils.getProperty("redirectUrl"))) {
                HttpUtil.postData(PropertiesUtils.getProperty("redirectUrl"), sendMsg);
            }
        }
        return new ResultModel<Object>("问卷保存成功");
    }

    // 计算生长发育百分比
    @ResponseBody
    @RequestMapping("/getGrowthPercentiles")
    public ResultModel<Object> getGrowthPercentiles(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        log.warn("in getGrowthPercentiles----arg==" + arg);

        JSONObject jsonObject = JSON.parseObject(arg);
        jsonObject = jsonObject.getJSONObject("data");
        if (jsonObject.isEmpty()) {
            return new ResultModel<Object>("查询数据错误");
        }
        Map<String, Object> jsonData = page(jsonObject);
        String tenantId = (String) jsonData.get("tenantId");

        String userId = (String) jsonData.get("userId");
        if (StringUtils.isEmpty(userId)) {
            log.debug("out getGrowthPercentiles----arg== null");
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，用户ID不能为空");
        }

        String type = (String) jsonData.get("type");
        if (StringUtils.isEmpty(type)) {
            log.debug("out getGrowthPercentiles----arg== null");
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，type不能为空");
        }

        String values = (String) jsonData.get("values");
        if (StringUtils.isEmpty(values)) {
            log.debug("out getGrowthPercentiles----arg== null");
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，values不能为空");
        }

        String testTime = (String) jsonData.get("testTime");
        if (StringUtils.isEmpty(testTime)) {
            log.debug("out getGrowthPercentiles----arg== null");
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，监测时间不能为空");
        }
        try {
            DateUtil.getDate_8(testTime);
        } catch (Exception e) {
            log.debug("out getGrowthPercentiles----arg== null");
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，监测时间格式不正确");
        }

        jsonData.put("authorId", "999");
        jsonData.put("tenantId", tenantId);
        String ageType = null;
        //2022年04月06日 西交大按照实际年龄计算
        if (tenantId.equals("xaefynewJCEBta001")) {
            ageType = Constants.GROWTH_AGE_TYPE_ACTUAL;
        }
        Map<String, Object> retOut = familyReportService.getGrowthPercentiles(jsonData, ageType, null);
        log.warn("out getGrowthPercentiles----arg==" + retOut);
        return new ResultModel<Object>(retOut);
    }

    // 患者信息List查询
    @ResponseBody
    @RequestMapping("/patientQueueListQuery")
    public ResultModel<Object> qryPatientQueueSchemeList(@RequestBody String arg,
                                                         HttpServletRequest request) throws Exception {
        log.warn("in qryPatientQueueSchemeList----arg==" + arg);

        JSONObject jsonObject = JSON.parseObject(arg);
        jsonObject = jsonObject.getJSONObject("data");
        if (jsonObject.isEmpty()) {
            return new ResultModel<Object>("查询数据错误");
        }
        Map<String, Object> jsonData = page(jsonObject);
        String tenantId = (String) jsonData.get("tenantId");

        HashMap<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("tenantId", tenantId);

        Integer ageTo = (Integer) jsonData.get("ageTo");
        Integer ageFrom = (Integer) jsonData.get("ageFrom");

        Calendar to = Calendar.getInstance();
        if (ageTo != null) {
            to.add(Calendar.MONTH, -ageTo);
            paramMap.put("ageTo", DateUtil.getDate_8(to.getTime()));
        }

        Calendar from = Calendar.getInstance();
        if (ageFrom != null) {
            from.add(Calendar.MONTH, -ageFrom);
            paramMap.put("ageFrom", DateUtil.getDate_8(from.getTime()));
        }

        String flag = (String) jsonData.get("flag");
        if (null == flag || "".equals(flag)) {
            // 默认查询当日待随访的患者
            flag = "0";
        }
        String phoneNo = (String) jsonData.get("phoneNum");
        String userName = (String) jsonData.get("patientName");// 可以是姓氏或姓名
        String userId = (String) jsonData.get("userId");
        String hisNo = (String) jsonData.get("hisNo");// 科研编号
        String fuzzyVar = (String) jsonData.get("fuzzyVar");// 姓名或科研编号
        if (!StringUtils.isEmpty(fuzzyVar)) {
            paramMap.put("fuzzyVar", fuzzyVar.replace(" ", "") + "%");
        }
        int page = (jsonData.get("page") == null || (int) jsonData.get("page") == 0) ? 1 : (int) jsonData.get("page");
        int rows = (jsonData.get("rows") == null || (int) jsonData.get("rows") == 0) ? 20 : (int) jsonData.get("rows");

        if (!StringUtils.isEmpty(phoneNo)) {
            paramMap.put("phoneNo", phoneNo);
        }
        if (!StringUtils.isEmpty(userId)) {
            paramMap.put("userId", userId);
        }
        if (!StringUtils.isEmpty(userName)) {
            paramMap.put("userName", userName);
            //增加通过拼音查询用户
            paramMap.put("namePinyin", userName.toLowerCase() + "%");
            //名字简拼
            paramMap.put("nameInitial", userName.toLowerCase() + "%");
        }
        paramMap.put("flag", flag);
        paramMap.put("start", (page - 1) * rows);
        paramMap.put("end", rows);

        // 增加队列id和患者来源
        paramMap.put("queueId", jsonData.get("queueId"));
        paramMap.put("sourceType", jsonData.get("opType"));
        paramMap.put("premature", jsonData.get("premature"));
        paramMap.put("qryEndTime", jsonData.get("qryEndTime"));
        paramMap.put("qryStartTime", jsonData.get("qryStartTime"));
        if (!StringUtils.isEmpty(hisNo)) {
            paramMap.put("hisNo", hisNo);
        }
        // 可以查询队列中正常状态患者，也可查询扫码建档待审核状态的患者
        String confirmFlag = (String) jsonData.get("confirmFlag");
        if (StringUtils.isNotEmpty(confirmFlag)) {
            paramMap.put("confirmFlag", confirmFlag);
        }
        paramMap.put("systemType", jsonData.get("systemType"));// 系统类型，00随访，01诊疗
        paramMap.put("taskAuditStatus", jsonData.get("taskAuditStatus"));

        // 针对Datatable特殊处理
        String jsonStr = (String) jsonData.get(Constants.INF_INPUTPARAM_DATATABLE_FIELD);
        int draw = 0;
        if (!StringUtils.isEmpty(jsonStr)) {
            JSONObject jsonTable = (JSONObject) JSONObject.parse(jsonStr);
            draw = jsonTable.getIntValue("draw");
            paramMap.put("start", jsonTable.getIntValue("start"));
            paramMap.put("end", jsonTable.getIntValue("length"));
        }

        // 特殊处理一妇婴倍力多项目
        paramMap.put("showFlag", jsonData.get("showFlag"));
        long time = System.currentTimeMillis();
        HashMap<String, Object> retMap = patientSerivce.qryPatientQueueSchemeList(paramMap);
        long time2 = System.currentTimeMillis();
        System.out.println("ceshi1789  : " + (time2 - time));
        // 针对Datatable特殊处理
        if (!StringUtils.isEmpty(jsonStr)) {
            retMap.put("draw", draw);
            retMap.put("recordsTotal", retMap.get("total"));
            retMap.put("recordsFiltered", retMap.get("total"));
        }

        return new ResultModel<Object>(retMap);
    }

    // 患者所在队列的任务list
    @ResponseBody
    @RequestMapping("/patientTaskListQuery")
    public ResultModel<Object> qryPatientTaskList(@RequestBody String arg) throws Exception {
        log.warn("in qryPatientTaskList----arg==" + arg);

        JSONObject jsonObject = JSON.parseObject(arg);
        jsonObject = jsonObject.getJSONObject("data");
        if (jsonObject.isEmpty()) {
            return new ResultModel<Object>("查询数据错误");
        }
        Map<String, Object> jsonData = page(jsonObject);

        HashMap<String, Object> paramMap = new HashMap<String, Object>();
        String ptSchemeId = (String) jsonData.get("patientSchemeId");
        if (null == ptSchemeId || "".equals(ptSchemeId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
                    "入参节点错误，未传入患者所在队列id或值为空！"));
        }
        String queueId = (String) jsonData.get("followQueueId");
        String userId = (String) jsonData.get("patientId");
        paramMap.put("ptSchemeId", ptSchemeId);
        paramMap.put("userId", userId);
        paramMap.put("queueId", queueId);
        // paramMap.put("orderBy", jsonData.get("orderBy"));// 排序，需要统一规则，这里先写死
        paramMap.put("seqNoOrderAsc", "1");
        paramMap.put("taskFlag", jsonData.get("taskFlag"));// 默认不传（查询截止到当天可以进行的任务），传了则查询所有任务
        paramMap.put("currDate", DateUtil.getCurrDate());
        if (!StringUtils.isEmpty((String) jsonData.get("seqNo"))) {
            paramMap.put("seqNo", jsonData.get("seqNo"));
        }
        if (null == paramMap.get("taskFlag")) {
            if (StringUtils.isNotEmpty(queueId)) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("id", queueId);
                FollowQueue queue = followQueueSerivce.getQueueDetailByQueueId(map);
                if (null == queue) {
                    throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_QUEUE_NOT_EXIST, "根据队列id查询无此队列信息！"));
                }
                String queueUserType = queue.getQueueUsertype();
                if (Constants.QUEUE_USER_TYPE_PARTURIENT.equals(queueUserType)) {
                    paramMap.put("taskFlag", "1");
                }
            }
        }
        List<Object> ptList = patientSerivce.qryPatientTaskList(paramMap);

        ArrayList<Object> ptListResult = new ArrayList<>();


        HashMap<String, Object> mapIn = new HashMap<>();
        for (Object o : ptList) {
            HashMap map = (HashMap) o;
            String taskId = (String) map.get("id");
            mapIn.put("taskId", taskId);
            List<PatientTaskContent> patientTaskContents = patientTaskContentDAO.selectContentByTaskId(mapIn);
            List<PatientTaskContent> taskContents = patientTaskContents.stream().filter(item -> item.getTemplType().equals("9")).collect(Collectors.toList());
            if (taskContents.size() > 0) {
                ptListResult.add(map);
            }
        }
        Collections.sort(ptListResult, new TaskComparatorDesc());    //重新排序这些随访任务。

        HashMap<String, Object> retMap = new HashMap<String, Object>();
        int total = 0;
        if (null != ptListResult) {
            total = ptListResult.size();
        }
        retMap.put("total", total);
        retMap.put("rows", ptListResult);

        return new ResultModel<Object>(retMap);
    }

    @ResponseBody
    @RequestMapping(value = "/xcxH5AddNewPatient")
    @Transactional
    public ResultModel<Object> xcxH5AddNewPatient(@RequestBody String args, HttpServletRequest request) throws Exception {

        log.warn("------------------------------进入xcxAddNewPatient-------------------------");
        String sendMsg = null;

        JSONObject jsonEsb = JSON.parseObject(args);
        JSONObject jsonArg = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
        if (null == jsonArg) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

        log.info("jsonArgs >>>>>>>>>>>>>> " + jsonArg);

        jsonArg = jsonArg.getJSONObject("params");

        // 小程序消息队列传入的type，判断是2.0建档还是3.0建档
        // 1作为2.0建档，3作为3.0建档
        // 8作为2.0随访门诊预约类型
        Integer type = jsonArg.getInteger("type");
        // code判断是否为发送消息
        String code = jsonArg.getString("code");
        if (type != null && type == 1 && code == null) {

            // 获取问卷内容
            Map<String, Object> quesMap = new HashMap<String, Object>();
            quesMap = jsonArg.getJSONObject("content");
            log.warn("------------------------------content-------------------------");
            String userId = jsonArg.getString("userId");
            String userIdNew = "";
            String queueId = jsonArg.getString("queueId");
            Map<String, Object> map = new HashMap<String, Object>();
            Map<String, Object> chkMapIn = new HashMap<String, Object>();
            boolean isVerify = true;
            map.put("id", queueId);
            chkMapIn.put("queueId", queueId);

            FollowQueue queue = followQueueSerivce.getQueueDetailByQueueId(map);
            if (null == queue) {
                sendMsg = "{\"type\":" + type + ",\"code\":\"" + ErrorCode.FOLLOWUP_EXCEPTION_TYPE_QUEUE_NOT_EXIST + "\",\"msg\":\"根据队列id查询无此队列信息！\",\"userId\":\"" + userId + "\"}";
                //mqttService.sendMessage(sendMsg);
                log.error("根据队列id查询无此队列信息！");
                //return;
                return new ResultModel<Object>(sendMsg);
            }
            log.warn("------------------------------queue-------------------------");
            String queueUserType = queue.getQueueUsertype();

            Map<String, Object> servParamMap = new HashMap<String, Object>();

            String author = "小程序建档";
            String authorName = "同步小程序建档";
            String tenantId = queue.getTenantId();
            String deptId = queue.getDeptId();

            // 操作编码默认：1000（患者建档）
            String opCode = "1000";
            // 操作类型默认：2（门诊）
            String opType = "2";
            // 患者来源渠道默认：9（小程序建档）
            String sourceType = Constants.PATIENT_SOURCE_TYPE_MINI_PROGRAM;
            String opNote = "小程序建档";
            // 创建时间
            String currTime = DateUtil.getTimeString(DateUtil.getSysDateA());

            String userType = null;
            if (Constants.QUEUE_USER_TYPE_BABY.equals(queueUserType)) {
                // 宝宝
                userType = "1";
                servParamMap.put("userType", userType);
            } else if (Constants.QUEUE_USER_TYPE_PARTURIENT.equals(queueUserType)) {
                // 孕产妇
                userType = "2";
                servParamMap.put("userType", userType);
            } else if (Constants.QUEUE_USER_TYPE_OTHER.equals(queueUserType)) {
                // 其他
                userType = "3";
                servParamMap.put("userType", userType);
            }

            Map<String, Object> userMap = new HashMap<>();

            String updateAccept = SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_SYSTEMID);// 操作流水

            String phoneNum = null;
            if (StringUtils.isBlank(phoneNum)) {
                if (null != quesMap && 0 != quesMap.size()) {
                    phoneNum = (String) quesMap.get(Constants.QUESTION_ID_FOR_PHONENO);
                }
            }
            if (StringUtils.isBlank(phoneNum)) {
                phoneNum = "";
                chkMapIn.put("quesId", Constants.QUESTION_ID_FOR_PHONENO);
                isVerify = patientArchService.isVerifyArchiveParam(chkMapIn);
                if (isVerify) {
                    sendMsg = "{\"type\":" + type + ",\"code\":\"" + ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR + "\",\"msg\":\"手机号码不能为空！\",\"userId\":\"" + userId + "\"}";
                    return new ResultModel<Object>(sendMsg);
                    //throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "手机号码不能为空！"));
                }
            }
            phoneNum = phoneNum.trim();
            log.warn("------------------------------phone-------------------------");
            String patientName = null;
            if (StringUtils.isBlank(patientName)) {
                if (null != quesMap && 0 != quesMap.size()) {
                    patientName = (String) quesMap.get(Constants.QUESTION_ID_FOR_PATIENTNAME);
                }
            }
            if (StringUtils.isBlank(patientName)) {
                patientName = "";
                chkMapIn.put("quesId", Constants.QUESTION_ID_FOR_PATIENTNAME);
                isVerify = patientArchService.isVerifyArchiveParam(chkMapIn);
                if (isVerify) {
                    sendMsg = "{\"type\":" + type + ",\"code\":\"" + ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR + "\",\"msg\":\"患者姓名不能为空！\",\"userId\":\"" + userId + "\"}";
                    return new ResultModel<Object>(sendMsg);
                    //throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "患者姓名不能为空！"));
                }
            }
            patientName = patientName.trim();
            log.warn("------------------------------name-------------------------");
            String gender = null;
            if (Constants.QUEUE_USER_TYPE_PARTURIENT.equals(queueUserType)) {
                // 孕产妇（母亲）
                gender = Constants.GENDER_FOR_FEMALE;
            } else if (StringUtils.isBlank(gender)) {
                if (null != quesMap && 0 != quesMap.size()) {
                    gender = (String) quesMap.get(Constants.QUESTION_ID_FOR_GENDER);
                }
            }
            if (StringUtils.isBlank(gender)) {
                gender = "";
                chkMapIn.put("quesId", Constants.QUESTION_ID_FOR_GENDER);
                isVerify = patientArchService.isVerifyArchiveParam(chkMapIn);
                if (isVerify) {
                    sendMsg = "{\"type\":" + type + ",\"code\":\"" + ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR + "\",\"msg\":\"性别不能为空！\",\"userId\":\"" + userId + "\"}";
                    return new ResultModel<Object>(sendMsg);
                    //throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "性别不能为空！"));
                }
            }
            gender = gender.trim();
            // 转换性别
            if (Constants.GENDER_ALIAS_FOR_MALE.equals(gender)) {
                gender = Constants.GENDER_FOR_MALE;
            } else if (Constants.GENDER_ALIAS_FOR_FEMALE.equals(gender)) {
                gender = Constants.GENDER_FOR_FEMALE;
            } else if (!Constants.GENDER_FOR_MALE.equals(gender) && !Constants.GENDER_FOR_FEMALE.equals(gender)) {
                gender = Constants.GENDER_FOR_MALE;
            }
            log.warn("------------------------------gender-------------------------");
            String birthday = null;
            if (StringUtils.isBlank(birthday)) {
                if (null != quesMap && 0 != quesMap.size()) {
                    birthday = (String) quesMap.get(Constants.QUESTION_ID_FOR_BIRTHDAY);
                    // Excel获取年龄格式为yyyy-MM-dd HH:mm:ss处理成yyyy-MM-dd格式，方便后续时间节点计算
                    String[] birthdays = birthday.split(" ");
                    birthday = birthdays[0];
                }
            }
            if (StringUtils.isBlank(birthday) && !Constants.QUEUE_USER_TYPE_PARTURIENT.equals(queueUserType)) {
                birthday = null;
                chkMapIn.put("quesId", Constants.QUESTION_ID_FOR_BIRTHDAY);
                isVerify = patientArchService.isVerifyArchiveParam(chkMapIn);
                if (isVerify) {
                    sendMsg = "{\"type\":" + type + ",\"code\":\"" + ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR + "\",\"msg\":\"出生日期不能为空！\",\"userId\":\"" + userId + "\"}";
                    return new ResultModel<Object>(sendMsg);
                    //throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "出生日期不能为空！"));
                }
            }
            log.warn("------------------------------birthday-------------------------");
            // 预产期
            String expectedDay = null;
            if (StringUtils.isBlank(expectedDay)) {
                if (null != quesMap && 0 != quesMap.size()) {
                    expectedDay = (String) quesMap.get(Constants.QUESTION_ID_FOR_EXPECTEDDAY);
                }
            }
            if (StringUtils.isEmpty(expectedDay)) {
                expectedDay = null;
            }
            log.warn("------------------------------expectedDay-------------------------");
            // 出生胎龄(孕周)
            int pregnancyDay = 0;
            // 再考虑从问卷中获取，问卷存储格式天
            if (pregnancyDay <= 0 && !MapUtils.isEmpty(quesMap)) {
                pregnancyDay = Integer.parseInt((String) quesMap.get(Constants.QUESTION_ID_FOR_PREGNANCYDAY));
//                                String preStr = (String) quesMap.get(Constants.QUESTION_ID_FOR_PREGNANCYDAY);
//                                if (!StringUtils.isBlank(preStr)) {
//                                    String preArr[] = preStr.split(Constants.COMMA_SPLIT_STR);
//                                    if (null != preArr && 2 == preArr.length) {
//                                        String preWeekStr = preArr[0].substring(1);
//                                        String preDayStr = preArr[1].substring(0, preArr[1].length() - 1);
//                                        int preWeek = Integer.parseInt(preWeekStr);
//                                        int preDay = Integer.parseInt(preDayStr);
//                                        pregnancyDay = preWeek * Constants.PREGNANCY_CALC_UNIT_WEEK + preDay;
//                                    }
//                                }
            }
            // 最后根据根据生日和预产期计算
            if (Constants.QUEUE_USER_TYPE_PARTURIENT.equals(queueUserType)) {
                // 孕产妇（母亲）
                // 初检孕周
                String firstChkPregWeek = (String) quesMap.get(Constants.QUESTION_ID_FOR_PREGNANCY_FIRST_WEEK);
                if (StringUtils.isBlank(firstChkPregWeek)) {
                    // 不在这里校验，在实例化随访任务时校验
                } else {
                    servParamMap.put("firstChkPregWeek", Integer.parseInt(firstChkPregWeek));
                }
                // 末次月经日期
                String lastMenstruationDate = (String) quesMap.get(Constants.QUESTION_ID_FOR_LAST_MENSTRUATION_DATE);
                if (StringUtils.isBlank(lastMenstruationDate)) {
                    // 不在这里校验，在实例化随访任务时校验
                } else {
                    servParamMap.put("lastMenstruationDate", lastMenstruationDate);
                }
                // 分娩日期
                servParamMap.put("deliveryDate", quesMap.get(Constants.QUESTION_ID_FOR_LAST_DELIVERY_DATE));
            } else if (pregnancyDay <= 0 && !StringUtils.isBlank(expectedDay)) {
                pregnancyDay = ToolUtil.calPrenDayByBirthAndExpect(birthday, expectedDay);
            }

            // 孕周未填，默认280
            if (pregnancyDay <= 0) {
                pregnancyDay = Constants.PATIENT_NORMAL_PREGNANT_DAY;
            }
            // 预产期未填，默认与出生日期一致
            if (StringUtils.isBlank(expectedDay)) {
                expectedDay = birthday;
            }
            log.warn("------------------------------pregnancyDay-------------------- " + pregnancyDay);
            if (pregnancyDay > 321) {
                sendMsg = "{\"type\":" + type + ",\"code\":\"" + ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR + "\",\"msg\":\"出生日期或者预产期不正确，请检查！\",\"userId\":\"" + userId + "\"}";
                return new ResultModel<Object>(sendMsg);
                //throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"尊敬的用户，您填写的出生日期或者预产期不正确，请检查！");
            }
            log.warn("------------------------------生日或预产期-------------------------");
            // 防止重复新建患者
            Map<String, Object> qryPtMap = new HashMap<String, Object>();
            qryPtMap.put("phoneNo", phoneNum);
            qryPtMap.put("userName", patientName);
            qryPtMap.put("tenantId", tenantId);
            // 不同类型用户
            qryPtMap.put("userType", userType);
            List<Patient> ptList = iPatientDAO.selectByPhoneNo(qryPtMap);
            List<PatientQueueScheme> pqsList = new ArrayList<PatientQueueScheme>();
            if (!org.springframework.util.CollectionUtils.isEmpty(ptList)) {
                // 校验患者是否已经加入过该队列
                HashMap<String, Object> qryPqsMap = new HashMap<String, Object>();
                qryPqsMap.put("userId", ptList.get(0).getId());
                qryPqsMap.put("queueId", queueId);

                List<String> statulist = new ArrayList<String>();

                statulist.add(Constants.PATIENT_QUEUESCHEME_USER_STATUS_NOMAL);

                qryPqsMap.put("status", statulist);

                pqsList = iPatientQueueSchemeDAO.selectByUserId(qryPqsMap);
            }

            if (org.springframework.util.CollectionUtils.isEmpty(pqsList)) {
                log.warn("------------------------------pqsList-------------------------");
                Patient pt = new Patient();
                pt.setId(userId);
                pt.setPregnancyDay(pregnancyDay);
                pt.setUserName(patientName);
                pt.setPhoneNo(phoneNum);
                pt.setFirstName(patientName.substring(0, 1));
                pt.setCreateTime(currTime);
                pt.setUpdateTime(currTime);
                pt.setCreateAuthor(author);
                pt.setBirthday(birthday);
                pt.setExpectedDay(expectedDay);
                pt.setGender(gender);
                pt.setUserType(userType);
                pt.setSourceType(sourceType);

                try {
                    servParamMap.put("patient", pt);
                    servParamMap.put("authorName", authorName);
                    servParamMap.put("deptId", deptId);
                    servParamMap.put("queueId", queueId);
                    servParamMap.put("updateTime", currTime);
                    servParamMap.put("authorId", author);
                    servParamMap.put("updateAccept", updateAccept);
                    servParamMap.put("tenantId", tenantId);
                    servParamMap.put("opCode", opCode);
                    servParamMap.put("opNote", opNote);
                    servParamMap.put("opType", opType);
                    servParamMap.put("contentData", quesMap);
                    userMap = patientSerivce.registerPatient(servParamMap);
                    userIdNew = (String) userMap.get("patientId");
                    quesMap.clear();
                } catch (Exception ex) {
                    log.error(ex.getMessage());
                    sendMsg = "{\"type\":" + type + ",\"code\":\"" + ErrorCode.SMALL_PROGRAM_EXCEPTION_ARCHIVE_FAILURE + "\",\"msg\":\"同步建档失败！\",\"userId\":\"" + userId + "\"}";
                    JSONObject retMap = new JSONObject();
                    retMap.put("code", ErrorCode.SMALL_PROGRAM_EXCEPTION_ARCHIVE_FAILURE);
                    retMap.put("msg", "同步建档失败！");
                    log.warn("------------------------------同步建档失败-------------------------");
                    return new ResultModel<Object>(retMap);
                    //throw new AppException(ErrorCode.SMALL_PROGRAM_EXCEPTION_ARCHIVE_FAILURE, "同步建档失败！");
                }
            } else {
                //sendMsg = "{\"type\":" + type + ",\"code\":\"" + ErrorCode.SMALL_PROGRAM_EXCEPTION_ARCHIVE_FAILURE + "\",\"msg\":\"该类型用户在该队列下已建过档，不能重复建档！\",\"userId\":\"" + userId + "\"}";
                JSONObject retMap = new JSONObject();
                retMap.put("code", ErrorCode.SMALL_PROGRAM_EXCEPTION_ARCHIVE_FAILURE);
                log.warn("------------------------------存在,不能重复建档-------------------------");
                retMap.put("msg", "该类型用户在该队列下已建过档，不能重复建档！");
                return new ResultModel<Object>(retMap);
            }
            log.warn("------------------------------生日或预产期-------------------------");
            if (!userMap.isEmpty()) {
                String platType = departmentBasicService.getDepartmentBasicDetails(deptId).getPlatType();
                // sendMsg = "{\"type\":" + type + ",\"deptId\":\"" + deptId + "\",\"code\":\"0\",\"msg\":\"同步建档成功！\",\"userId\":\"" + userId + "\",\"tenantId\":\"" + tenantId + "\",\"platType\":"+
                // platType+",\"oriUserId\":\""+userId+"\"}";
                JSONObject retMap = new JSONObject();
                retMap.put("code", "0");
                retMap.put("type", type);
                retMap.put("deptId", deptId);
                retMap.put("userId", userIdNew);
                retMap.put("tenantId", tenantId);
                retMap.put("platType", platType);
                retMap.put("oriUserId", userId);
                log.warn("------------------------------同步建档成功-------------------------");
                return new ResultModel<Object>(retMap);
            }
        } else {
            log.info("不是2.0建档或2.0随访门诊预约，不做处理！");
        }
        return new ResultModel<Object>(null);
    }

    /**
     * 建档信息回显或建档信息修改
     * Edit Ace
     * date 2023-06-29
     */
    @ResponseBody
    @RequestMapping("/xcxPatientInfo")
    public ResultModel<Object> xcxPatientInfo(@RequestBody String args) throws Exception {
        JSONObject obj = JSON.parseObject(args);
        obj = obj.getJSONObject("data").getJSONObject("params");
        String userId = obj.getString("userId");
        if (userId == null) {
            return new ResultModel<>(null);
        }
        String queueId = obj.getString("queueId");
        if (null != obj.getString("exist")) {
            // 存在用户,进行修改
            JSONObject content = obj.getJSONObject("content");
            String tenantId = obj.getString("tenantId");
            Map<String, Object> userMapIn = new HashMap<String, Object>();
            userMapIn.put("userId", userId);
            userMapIn.put("tenantId", tenantId);
            userMapIn.put("updateTime", new Date());
            HashMap<String, Object> updateParam = MapUtil.newHashMap();
            for (Map.Entry<String, Object> entry : content.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue().toString().trim();
                // 手机号码
                if (key.equals(Constants.QUESTION_ID_FOR_PHONENO)) {
                    if (!StringUtils.isBlank(value)) {
                        userMapIn.put("phoneNo", value);
                    }
                }
                // 患者姓名
                if (key.equals(Constants.QUESTION_ID_FOR_PATIENTNAME)) {
                    if (!StringUtils.isBlank(value)) {
                        userMapIn.put("userName", value);
                    }
                    //更新名字拼音 2018-01-11
                    try {
                        userMapIn.put("namePinyin", ToolUtil.getEname(value));
                        userMapIn.put("nameInitial", ToolUtil.getNameInitial(value));
                    } catch (BadHanyuPinyinOutputFormatCombination e) {
                        userMapIn.put("namePinyin", null);
                        userMapIn.put("nameInitial", null);
                    }
                    userMapIn.put("firstName", value.substring(0, 1));
                }
                // 性别
                if (key.equals(Constants.QUESTION_ID_FOR_GENDER)) {
                    if (!StringUtils.isBlank(value)) {
                        // 转换性别
                        if (Constants.GENDER_ALIAS_FOR_MALE.equals(value) || value.startsWith(Constants.GENDER_ALIAS_FOR_MALE)) {
                            value = Constants.GENDER_FOR_MALE;
                        } else if (Constants.GENDER_ALIAS_FOR_FEMALE.equals(value) || value.startsWith(Constants.GENDER_ALIAS_FOR_FEMALE)) {
                            value = Constants.GENDER_FOR_FEMALE;
                        } else if (!Constants.GENDER_FOR_MALE.equals(value) && !Constants.GENDER_FOR_FEMALE.equals(value)) {
                            value = Constants.GENDER_FOR_MALE;
                        }
                        userMapIn.put("gender", value);
                    }
                }
                // 出生日期
                if (key.equals(Constants.QUESTION_ID_FOR_BIRTHDAY)) {
                    if (!StringUtils.isBlank(value)) {
                        userMapIn.put("birthday", value);
                    }
                }
                // 预产期
                if (key.equals(Constants.QUESTION_ID_FOR_EXPECTEDDAY)) {
                    if (!StringUtils.isBlank(value)) {
                        userMapIn.put("expectedDay", value);
                    }
                }
                if (key.equals(Constants.QUESTION_ID_FOR_IDCARD)) {
                    if (!StringUtils.isBlank(value)) {
                        userMapIn.put("idCard", value);
                    }
                }
                if (key.equals(Constants.QUESTION_ID_FOR_PREGNANCYDAY)) {
                    if (!StringUtils.isBlank(value)) {
                        userMapIn.put("pregnancyDay", value);
                    }
                }
                if (key.equals(Constants.QUESTION_ID_FOR_INPATIENT_NO)) {
                    if (!StringUtils.isBlank(value)) {
                        userMapIn.put("hospitalNo", value);
                    }
                }
                updateParam.put("questionAnswer", entry.getValue());
                updateParam.put("questionId", entry.getKey());
                updateParam.put("tenantId", tenantId);
                updateParam.put("userId", userId);
                patientTaskContentDAO.updateAnswerByTenantIdAndUserIdAndQuestionId(updateParam);
            }

            // 不存在的问卷信息需要插入
            HashMap<String, Object> qryMap = new HashMap<>();
            qryMap.put("userId", userId);
            qryMap.put("tenantId", tenantId);
            List<PatientContentData> dataList = patientTaskContentDAO.listByCondition(qryMap);
            List<String> keyList = new ArrayList<>();
            for (PatientContentData data : dataList) {
                keyList.add(data.getQuestionId());
            }
            if (!keyList.isEmpty()) {
                for (String key : keyList) {
                    content.remove(key);
                }
            }

            if (!content.isEmpty()) {
                List<PatientContentData> insertList = new ArrayList<>();
                for (Map.Entry<String, Object> entry : content.entrySet()) {
                    PatientContentData patientContentData = new PatientContentData();
                    PatientContentData source = dataList.get(0);
                    BeanUtils.copyProperties(source, patientContentData);
                    patientContentData.setId(SeqUtil.getSeqNo());
                    patientContentData.setQuestionId(entry.getKey());
                    patientContentData.setQuestionAnswer((String) entry.getValue());
                    insertList.add(patientContentData);
                }
                patientTaskContentDAO.insertContentDataBatch(insertList);
            }

            userMapIn.remove("tenantId");
            iPatientDAO.updatePatientInfoById(userMapIn);
        }
        Map<String, Object> queueSchemeQryMap = new HashMap<>();
        queueSchemeQryMap.put("userId", userId);
        queueSchemeQryMap.put("queueId", queueId);
        List<PatientQueueScheme> patientQueueSchemes = patientQueueSchemeDAO.selectByUserId(queueSchemeQryMap);
        if (!patientQueueSchemes.isEmpty()) {
            String ptSchemeId = patientQueueSchemes.get(0).getId();
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("ptSchemeId", ptSchemeId);
            paramMap.put("userId", userId);
            paramMap.put("queueId", queueId);
            // paramMap.put("orderBy", jsonData.get("orderBy"));// 排序，需要统一规则，这里先写死
            paramMap.put("seqNoOrderAsc", "1");
            paramMap.put("taskFlag", obj.getString("taskFlag"));// 默认不传（查询截止到当天可以进行的任务），传了则查询所有任务
            paramMap.put("currDate", DateUtil.getCurrDate());
            Map<String, Object> result = new HashMap<>();
            List<Object> ptList = patientSerivce.qryPatientTaskList(paramMap);
            if (!ptList.isEmpty()) {
                // 升序排序后建档信息索引值为0
                String jsonStr = JSON.toJSONString(ptList.get(0));
                JSONObject ptTaskInfo = JSON.parseObject(jsonStr);
                String taskId = ptTaskInfo.getString("taskId");
                Map<String, Object> taskQryMap = new HashMap<>();
                taskQryMap.put("taskId", taskId);
                List<PatientContentData> contentDataList = patientTaskContentDAO.selectContentDataByTaskId(taskQryMap);
                if (!contentDataList.isEmpty()) {
                    for (PatientContentData data : contentDataList) {
                        result.put(data.getQuestionId(), data.getQuestionAnswer());
                    }
                    log.info("result >>>>>>>>>>>>>>> " + result);
                    return new ResultModel<>(JSON.toJSONString(result));
                }
            }
        }
        return new ResultModel<>(null);
    }

    /**
     * 获取队列方案
     * Edit Ace
     * date 2023-07-05
     */
    @ResponseBody
    @RequestMapping("/xcxQueueScheme")
    public ResultModel<Object> xcxQueueScheme(@RequestBody String args) throws Exception {
        JSONObject jsonObject = JSON.parseObject(args);
        jsonObject = jsonObject.getJSONObject("data").getJSONObject("params");
        List<PatientQueueScheme> patientQueueSchemes = patientQueueSchemeDAO.selectByUserId(jsonObject);
        if (!patientQueueSchemes.isEmpty()) {
            PatientQueueScheme patientQueueScheme = patientQueueSchemes.get(0);
            return new ResultModel<>(patientQueueScheme);
        }
        return new ResultModel<>(null);
    }

    @PostMapping("/sendMessage")
    public ResultModel sendMessage(@RequestBody String arg, HttpServletRequest request) throws Exception {
        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            // 后续重写异常类
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参节点错误，非json格式！"));
        }
        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回（后续重写异常类）
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

        // 从session中获取，这里先写死
        Map<String, Object> session = ToolUtils.getSessionInfo(request);
        String authorId = (String) session.get("authorId");
        String tenantId = (String) session.get("tenantId");
        String authorName = (String) session.get("authorName");
        String deptId = (String) session.get("deptId");

        String platType = departmentBasicService.getDepartmentBasicDetails(deptId).getPlatType();
        String userId = jsonData.getString("userId");
        String userName = jsonData.getString("userName");
        String content = jsonData.getString("content");

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("userId", userId);
        jsonObject.put("userName", userName);
        jsonObject.put("content", content);
        jsonObject.put("platType", Integer.parseInt(platType));
        jsonObject.put("tenantId", tenantId);
        jsonObject.put("type", 22);

        messageNotifyRecordService.sendMessage(jsonObject);
        return new ResultModel("发送成功");
    }

    @ResponseBody
    @RequestMapping(value = "/getXcxPlatType")
    public ResultModel getXcxPlatType(@RequestBody String requestBody) {
        log.info("6-->" + requestBody);
        JSONObject jsonObject = JSON.parseObject(requestBody);
        String platType = null;
        try {
            platType = departmentBasicService.getDepartmentBasicDetails(String.valueOf(jsonObject.get("deptId"))).getPlatType();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResultModel<Object>(platType);
    }

}
